package com.zq.it.service.impl.exam;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zq.it.dao.common.PageConfig;
import com.zq.it.pojo.Student;
import com.zq.it.pojo.exam.TExam;
import com.zq.it.pojo.exam.TExamResult;
import com.zq.it.pojo.exam.TPaper;
import com.zq.it.pojo.exam.TPaperDetail;
import com.zq.it.pojo.exam.TPaperSection;
import com.zq.it.pojo.exam.data.ExamResultData;
import com.zq.it.pojo.exam.data.ObjectData;
import com.zq.it.pojo.exam.data.PaperData;
import com.zq.it.service.common.BaseServiceImpl;
import com.zq.it.service.exam.ExamService;
import com.zq.it.tool.Constant;
import com.zq.it.tool.ExamUtil;
import com.zq.it.tool.StringUtil;

import net.sf.json.JSONArray;

public class ExamServiceImpl extends BaseServiceImpl implements ExamService {

	@Override
	public ObjectData getMyExamList(PageConfig config) {
		ObjectData objList = getListByPage(config);
		List<TExamResult> list = objList.getList();
		List<ExamResultData> dataList = new ArrayList<ExamResultData>();
		ExamResultData temp = null;
		for (TExamResult ter : list) {
			temp = new ExamResultData();
			temp.setExamResult(ter);
			temp.setPaper(paperDAO.findById(ter.getPId()));
			dataList.add(temp);
		}
		objList.setList(dataList);
		return objList;
	}

	@Override
	public Long getLeftTimeByPaperId(long id) {
		TPaper paper = paperDAO.findById(id);
		return (paper.getEndTime().getTime() - new Date().getTime()) / 1000;
	}

	@Override
	public String addValidateAndSubmitMyExam(Long examResultId, Student student,
			PaperData paperData, HttpServletRequest request,
			HttpServletResponse response) {
		List list = new ArrayList();
		int TOTAL_SCORE = 0;
		List<TPaperSection> LIST_SECTIONS = paperData.getPaperSections();
		if ((LIST_SECTIONS != null) && (LIST_SECTIONS.size() > 0)) {
			for (TPaperSection section : LIST_SECTIONS) {
				List<TPaperDetail> paperDetails = paperData.getPaperDetail();
				if ((paperDetails != null) && (paperDetails.size() > 0)) {
					for (TPaperDetail detail : paperDetails) {
						if (detail.getTPaperSection().getId() != section
								.getId())
							continue;
						String[] ArrUserKey = request.getParameterValues(
								"question_" + detail.getTQuestions().getId());
						String UserKey = "";
						boolean UserKeyIsTure = false;
						int Qtype = detail.getTQuestions().getQType();
						int Qscore = detail.getScore();
						int iQscore = 0;
						if ((ArrUserKey != null) && (ArrUserKey.length > 0)) {
							List ls;
							JSONArray jsonArray;
							if (Constant.QTYPE_BLANK == Qtype) {
								int ix = 1;
								ls = new ArrayList();
								for (String s : ArrUserKey) {
									Map _map = new HashMap();
									_map.put("ID", ix);
									_map.put("VAL", StringUtil.trim(s));
									ls.add(_map);
									ix++;
								}
								jsonArray = JSONArray.fromObject(ls);
								UserKey = jsonArray.toString();
							} else {
								int keyNum = ArrUserKey.length;
								for (int i = 0; i < keyNum; i++) {
									UserKey = UserKey + ArrUserKey[i];
								}
							}

						}

						if ((Constant.QTYPE_SELECT == Qtype)
								|| (Constant.QTYPE_JUDGE == Qtype)) {
							if (detail.getTQuestions().getSkey() != null) {
								UserKeyIsTure = detail.getTQuestions().getSkey()
										.equals(UserKey);
							}
						} else if (Constant.QTYPE_BLANK == Qtype) {
							double discore = 0.0d;
							discore = Qscore * ExamUtil.CompareJSON(
									detail.getTQuestions().getSkey(), UserKey);
							iQscore = (int) discore;
						}
						if (UserKeyIsTure) {
							iQscore = Qscore;
						}
						TOTAL_SCORE += iQscore;
						list.add(new TExam(detail.getTQuestions(), student,
								paperData.getPaper(), UserKey, iQscore, Qtype,
								null));
					}
				}
			}
		}

		if ((list != null) && (list.size() > 0)) {
			TExamResult examResult = examResultDAO.findById(examResultId);
			examResult.setScore(TOTAL_SCORE);
			examResultDAO.update(examResult);
			examDAO.deleteByHql("delete from TExam exam where exam.Student.id="
					+ student.getId() + " and exam.TPaper.id="
					+ paperData.getPaper().getId());
			examDAO.saveAll(list);
			return "试卷提交成功！";
		} else {
			return "提交的试卷为空！";
		}
	}

	@Override
	public Map getMyExamResult(Long id, Student student) {
		List<TExam> data = null;
		Map map = null;
		TExamResult examResult = examResultDAO.findById(id);
		TPaper paper = paperDAO.findById(examResult.getPId());
		long stuId = examResult.getStudent().getId();
		if (stuId != student.getId()) {
			return null;
		}
		data = examDAO.findByHql("from TExam exam where exam.TPaper.id =" + paper.getId() + " and exam.Student.id=" + stuId + "");
		map = new HashMap();
		map.put("paper_id", paper.getId());
		map.put("student_id", stuId);
		map.put("exam_result_id", examResult.getId());
		map.put("student_total_score", examResult.getScore());
		for (TExam exam : data) {
			map.put(exam.getTPaper().getId() + "_" + exam.getTQuestions().getId(), exam);
		}
		if (null == data || data.size() == 0) {
			map.put("data_check", false);
		} else {
			map.put("data_check", true);
		}
		return map;
	}

	@Override
	public String creatMyExamHql(TPaper paper, Integer state, Student student) {
		String stateHql = null;
		Date nowTime = new Date();
		SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String pnameHql = paper.getPName() == null || paper.getPName().isEmpty()
				? ""
				: " and p.PName like '%" + paper.getPName() + "%'";
		switch (state) {
			case -1 :
				stateHql = "";
				break;
			case 0 :
				stateHql = " and p.postDate >'" + formater.format(nowTime)
						+ "'";
				break;
			case 1 :
				stateHql = " and p.postDate <'" + formater.format(nowTime)
						+ "'";
				break;
			default :
				stateHql = "";
				break;
		}
		StringBuffer hql = new StringBuffer(
				"from TExamResult as t where exists(select 1 from TPaper p where t.PId=p.id "
						+ pnameHql + " " + stateHql + ")  and t.student.id="
						+ student.getId());
		return hql.toString();
	}
}
